package com.lungle.warmdiary.app.api.exception;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.lungle.warmdiary.app.AppContext;
import com.lungle.warmdiary.app.ui.dialog.DialogHelper;
import com.lungle.warmdiary.app.utils.LogUtils;
import com.lungle.warmdiary.app.view.me.LoginActivity;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import retrofit2.adapter.rxjava.HttpException;

/**
 * @author sbbic
 *         created at 2016/9/11 21:29
 */
public class ApiErrorHelper {

    public static void showErrorDetail(String errorMsg) {
        if (TextUtils.isEmpty(errorMsg)) {
            return;
        }
        JsonObject jsonObject = new JsonParser().parse(errorMsg).getAsJsonObject();
        Set<Map.Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
        Iterator<Map.Entry<String, JsonElement>> ite = entrySet.iterator();
        boolean isShow = false;
        while (ite.hasNext() && !isShow) {
            Map.Entry<String, JsonElement> entry = ite.next();
            JsonElement value = entry.getValue();
            if (!value.isJsonNull() && value.isJsonArray()) {
                JsonArray asJsonArray = value.getAsJsonArray();
                if (asJsonArray.size() <= 0) continue;
                JsonElement jsonElement = asJsonArray.get(0);
                AppContext.showToast(jsonElement.getAsString());
                isShow = true;
            }

        }
    }


    public static void handleCommonError(Context context, Throwable e) {

        e.printStackTrace();
        if (e instanceof HttpException) {
            AppContext.showToastShort("服务暂不可用");
        } else if (e instanceof IOException) {
            LogUtils.printLogI("服务暂不可用");
        } else if (e instanceof ApiException) {
            handleApiError(context, e);
        } else {
            AppContext.showToast("出现问题");
        }


    }

    private static void handleApiError(Context context, Throwable e) {
        ApiException exception = (ApiException) e;
        switch (exception.getErrorCode()) {
            case ApiErrorCode.ERROR_CLIENT_AUTHORIZED:
                AppContext.showToast("非法客户端");
                break;
            case ApiErrorCode.ERROR_NO_INTERNET:
                AppContext.showToastShort("无网络连接");
                break;
            case ApiErrorCode.ERROR_OTHER:
                AppContext.showToastShort(exception.getMessage());
                break;
            case ApiErrorCode.ERROR_PARAM_CHECK:
                LogUtils.printLogE("param check error:" + exception.getMessage());
                break;
            case ApiErrorCode.ERROR_REQUEST_PARAM:
                LogUtils.printLogE("param request error:" + exception.getMessage());
                break;
            case ApiErrorCode.ERROR_USER_AUTHORIZED:
                reLogin(context);
                break;
            default:
                AppContext.showToastShort("发生了一点问题，稍后再试");
                break;
        }


    }

    private static void reLogin(final Context context) {

        if (!AppContext.shouldShowReloadin) return;
        AppContext.shouldShowReloadin = false;
        if (context != null && context instanceof Activity) {
            AlertDialog.Builder reLoginDialog = DialogHelper.getMessageDialog(context, "您的帐号在其他设备登录，请重新登录", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    Intent intent = new Intent(context, LoginActivity.class);
//                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    intent.putExtra(LoginActivity.BUNDLE_KEY_REQUEST_CODE, LoginActivity.REQUEST_CODE_RELOGIN);
                    AppContext.getInstance().Logout();
                    context.startActivity(intent);
                }
            });

            reLoginDialog.setCancelable(false);
            reLoginDialog.show();
        }
    }
}
